<template>
  <div class="address-manage">
    <van-nav-bar
      title="地址管理"
      left-arrow
      @click-left="goBack"
      fixed
    />
    
    <div class="content">
      <div v-if="addresses.length > 0" class="address-list">
        <div 
          v-for="address in addresses" 
          :key="address.addressId" 
          class="address-item"
          :class="{'address-item--selected': address.isDefault === 1}"
        >
          <div class="address-info">
            <div class="address-header">
              <span class="name">{{ address.recipientName }}</span>
              <span class="phone">{{ maskPhone(address.phone) }}</span>
              <span class="tag" :class="`tag-${address.type}`">{{ getAddressTypeText(address.type) }}</span>
            </div>
            <div class="address-content">
              {{ formatAddress(address) }}
            </div>
            <div class="address-action">
              <van-checkbox 
                :model-value="address.isDefault === 1"
                @click="setDefault(address.addressId)"
                shape="square"
                icon-size="18px"
                class="default-checkbox"
              >
                设为默认地址
              </van-checkbox>
            </div>
          </div>
          <div class="address-operations">
            <span class="edit" @click="onEdit({id: address.addressId}, 0)">编辑</span>
            <span class="delete" @click="deleteAddress(address.addressId)">删除</span>
          </div>
        </div>
      </div>
      
      <div v-else class="empty-tips">
        <p>暂无收货地址，请添加</p>
      </div>
      
      <div class="add-address">
        <van-button type="primary" block round @click="addNewAddress">
          <van-icon name="plus" /> 新增收货地址
        </van-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { api } from '../network/api';
import { showToast, showDialog } from 'vant';

// 定义API响应接口
interface ApiResponse {
  code: number;
  message: string;
  data?: any;
}

// 定义地址接口
interface Address {
  addressId: number;
  userId: string;
  recipientName: string;
  phone: string;
  province: string;
  city: string;
  district: string;
  detailedAddress: string;
  isDefault: number; // 0或1
  type?: string; // 可选字段，用于UI显示
}

export default defineComponent({
  name: 'AddressManageView',
  
  setup() {
    const router = useRouter();
    const addresses = ref<Address[]>([]);
    const defaultAddressId = ref<string | number>('');
    const isLoading = ref(false);
    const userId = ref<string>('');
    
    // 获取用户ID
    const getUserId = () => {
      try {
        const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
        return userInfo.data?.userId || userInfo.data?.id || userInfo.userId || userInfo.id;
      } catch (e) {
        console.error('解析用户信息失败:', e);
        return '';
      }
    };
    
    // 获取地址列表
    const getAddresses = async () => {
      try {
        isLoading.value = true;
        // 获取用户ID
        userId.value = getUserId();
        if (!userId.value) {
          console.warn('获取用户信息失败，但继续执行');
        }
        
        try {
          // 调用API获取地址列表
          const response = await api.getUserAddresses(userId.value || '0') as unknown as ApiResponse;
          console.log('API原始响应:', response);
          
          // 初始化为空地址列表
          addresses.value = [];
          defaultAddressId.value = '';
          
          // 检查API响应格式 - 使用正确的response结构
          if (response && response.code === 100) {
            console.log('API响应成功:', response.data);
            
            // 处理地址数据
            const addressData = response.data;
            
            if (addressData) {
              // 如果地址数据不是数组，转换为数组处理
              const addressList = Array.isArray(addressData) ? addressData : [addressData];
              console.log('处理的地址数据列表:', addressList.length, '条记录');
              
              if (addressList.length > 0) {
                // 转换为标准地址对象格式
                addresses.value = addressList.map((item: any) => {
                  const address: Address = {
                    addressId: item.addressId || item.address_id || item.id || 0,
                    userId: item.userId || item.user_id || userId.value,
                    recipientName: item.recipientName || item.recipient_name || item.name || '未命名',
                    phone: item.phone || item.tel || '',
                    province: item.province || item.provinceName || '',
                    city: item.city || item.cityName || '',
                    district: item.district || item.districtName || '',
                    detailedAddress: item.detailedAddress || item.detailed_address || item.detail || '',
                    isDefault: typeof item.isDefault === 'number' ? item.isDefault : 
                              (item.isDefault === true || item.is_default === true || item.isDefault === '1' || item.is_default === '1') ? 1 : 0,
                    type: item.type || 'home'
                  };
                  return address;
                });
                
                console.log('处理后的最终地址列表:', addresses.value);
                
                // 设置默认地址ID
                const defaultAddress = addresses.value.find((addr) => addr.isDefault === 1);
                if (defaultAddress) {
                  defaultAddressId.value = defaultAddress.addressId;
                  console.log('设置默认地址ID:', defaultAddressId.value);
                }
              } else {
                console.log('地址列表为空');
              }
            } else {
              console.log('未找到有效的地址数据');
            }
          } else {
            console.warn('API响应代码不为100，未处理数据');
          }
        } catch (apiError) {
          console.error('API调用出错:', apiError);
        }
      } catch (error) {
        console.error('获取地址列表过程中发生未知错误:', error);
      } finally {
        isLoading.value = false;
      }
    };
    
    // 设置默认地址
    const setDefault = async (addressId: number) => {
      try {
        if (!userId.value) {
          userId.value = getUserId();
          if (!userId.value) {
            showToast('获取用户信息失败');
            return;
          }
        }
        
        console.log(`设置默认地址: addressId=${addressId}, userId=${userId.value}`);
        
        // 确保userId是整数
        const userIdInt = parseInt(userId.value);
        if (isNaN(userIdInt)) {
          showToast('用户ID格式错误');
          return;
        }
        
        const response = await api.setDefaultAddress(addressId, userIdInt.toString()) as unknown as ApiResponse;
        console.log('设置默认地址API响应:', response);
        
        // 直接检查response.code
        if (response && response.code === 100) {
          // 更新本地数据
          addresses.value = addresses.value.map((address: Address) => ({
            ...address,
            isDefault: address.addressId === addressId ? 1 : 0
          }));
          defaultAddressId.value = addressId;
          showToast('设置成功');
        } else {
          showToast('设置默认地址失败');
        }
      } catch (error) {
        console.error('设置默认地址失败', error);
        showToast('设置默认地址失败');
      }
    };
    
    // 地址选择事件
    const onSelect = (addressId: number) => {
      setDefault(addressId);
    };
    
    // 编辑地址事件
    const onEdit = (item: {id: number}, index: number) => {
      editAddress(Number(item.id));
    };
    
    // 编辑地址
    const editAddress = (addressId: number) => {
      router.push(`/address/edit/${addressId}`);
    };
    
    // 删除地址
    const deleteAddress = async (addressId: number) => {
      try {
        await showDialog({
          title: '确认删除',
          message: '确定要删除该地址吗？',
          showCancelButton: true,
        });
        
        if (!userId.value) {
          userId.value = getUserId();
          if (!userId.value) {
            showToast('获取用户信息失败');
            return;
          }
        }
        
        const response = await api.deleteAddress(addressId, userId.value) as unknown as ApiResponse;
        console.log('删除地址API响应:', response);
        
        // 直接检查response.code，不再检查response.data
        if (response && response.code === 100) {
          // 从本地数据中移除
          addresses.value = addresses.value.filter((address: Address) => address.addressId !== addressId);
          showToast('删除成功');
        } else {
          showToast('删除地址失败');
        }
      } catch (error) {
        if (error === 'cancel') return; // 用户取消操作
        
        console.error('删除地址失败', error);
        showToast('删除地址失败');
      }
    };
    
    // 新增地址
    const addNewAddress = () => {
      router.push('/address/add');
    };
    
    // 返回个人资料页
    const goBack = () => {
      router.push('/profile');
    };
    
    // 电话号码脱敏处理
    const maskPhone = (phone: string) => {
      if (!phone || phone.length < 11) return phone;
      return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
    };
    
    // 获取地址类型文本
    const getAddressTypeText = (type: string | undefined) => {
      const typeMap: Record<string, string> = {
        'home': '家',
        'company': '公司',
        'other': '其他'
      };
      return type ? (typeMap[type] || '其他') : '其他';
    };
    
    // 格式化地址
    const formatAddress = (address: Address) => {
      return `${address.province}${address.city}${address.district}${address.detailedAddress}`;
    };
    
    onMounted(() => {
      getAddresses();
    });
    
    return {
      addresses,
      defaultAddressId,
      isLoading,
      setDefault,
      editAddress,
      deleteAddress,
      addNewAddress,
      goBack,
      maskPhone,
      getAddressTypeText,
      formatAddress,
      onEdit,
      onSelect,
      userId
    };
  }
});
</script>

<style scoped>
.address-manage {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.content {
  padding-top: 46px; /* 导航栏高度 */
  padding-bottom: 80px; /* 底部按钮区域高度 */
}

.address-item {
  background-color: #fff;
  margin: 10px;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  position: relative;
}

.address-item--selected {
  border: 1px solid #3490dc;
}

.address-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.name {
  font-size: 16px;
  font-weight: 500;
  margin-right: 10px;
}

.phone {
  color: #666;
}

.tag {
  margin-left: auto;
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
  color: #fff;
  background-color: #3490dc;
}

.tag-home {
  background-color: #3490dc;
}

.tag-company {
  background-color: #4caf50;
}

.tag-other {
  background-color: #ff9800;
}

.address-content {
  color: #333;
  font-size: 14px;
  line-height: 1.5;
  padding-right: 20px;
  margin-bottom: 10px;
}

.address-action {
  display: flex;
  align-items: center;
  color: #666;
  font-size: 13px;
  margin-top: 5px;
}

.default-checkbox {
  font-size: 14px;
}

.address-operations {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #eee;
}

.edit, .delete {
  font-size: 14px;
  color: #666;
  padding: 5px 15px;
  cursor: pointer;
}

.edit {
  border-right: 1px solid #eee;
}

.empty-tips {
  text-align: center;
  padding: 30px 0;
  color: #999;
}

.add-address {
  position: fixed;
  bottom: 20px;
  left: 15px;
  right: 15px;
}

:deep(.van-button--primary) {
  background-color: #3490dc;
  border-color: #3490dc;
}

:deep(.van-checkbox__icon--checked .van-icon) {
  background-color: #3490dc;
  border-color: #3490dc;
}
</style>